package org.BUPT.domain.service.impl;


import org.BUPT.domain.service.QuestionService;
import org.BUPT.infrastructure.persistent.DAO.*;
import org.BUPT.infrastructure.persistent.po.*;
//import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;
@Component

public class QuestionServiceImpl  implements QuestionService {

    @Autowired
    QuestionDAO questionDAO;

    @Autowired
    AnswerDAO answerDAO;

    @Autowired
    Question_TagDAO question_tagDAO;

    @Autowired
    SubscribeDAO subscribeDAO;



    public Question getQuestion(int questionId){
        // 注意，如果在数据库中未找到对象会返回null，要注意判断
        // 如果有需求这里可以改成返回new Question()

        return questionDAO.findQuestionByIdAndIsDel(questionId,0);
    }










    public List<String> getTagsOfQuestion(int questionId){ return question_tagDAO.getTagNamesByQuestionId(questionId);}


    public List<Question> getSubscribedQuestions(int userId){
        return subscribeDAO.getSubscribedQuestionsByUserId(userId);
    }
    public List<Question> getAskedQuestions(int userId){
        return questionDAO.findQuestionsByUserIdAndIsDel(userId,0);
    }



    public List<Answer> getAnswersOfQuestion(int questionId){
        return answerDAO.findAllByQuestionIdAndIsDel(questionId,0);
    }
    public int getAnswersNum(int questionId){
        return answerDAO.countAnswerByQuestionIdAndIsDel(questionId,0);
    }

    public List<Question> getPage(int pageId){
        Pageable pageable = PageRequest.of(pageId,7);
        return questionDAO.findQuestionsByIsDel(0,pageable).getContent();
    }



    public void subscribeQuestion(int userId, int questionId){subscribeDAO.save(
            new Subscribe()
            .setSubscribePrimaryKey(
                    new SubscribePrimaryKey()
                            .setUserId(userId)
                            .setQuestionId(questionId)
            ));}
    public void addQuestionTag(Question_Tag question_tag){ question_tagDAO.save(question_tag); }


    public Question saveQuestion(Question question){
        return questionDAO.save(question);
    }


    public void unSubscribe(int userId, int questionId){subscribeDAO.delete(
            new Subscribe()
            .setSubscribePrimaryKey(
                    new SubscribePrimaryKey()
                            .setUserId(userId)
                            .setQuestionId(questionId)
            ));}


    public List<Integer> getSubscribedUserOfQuestion(int questionId){
        return subscribeDAO.getSubscribedUsersOfQuestion(questionId);
    }

}
